import React, {FC, useEffect, useRef, useState, UIEvent} from 'react'
import {
    Button,
    Table,
    Input,
    Select,
    message,
    Cascader,
    Tag,
    Drawer,
    Form,
    InputNumber,
    Typography,
    Popconfirm
} from "antd";
import {useRequest} from "@umijs/hooks";
import {fetchRequest} from "@/utils/Request";
import {url} from "@/utils/url";
import {getOriginString} from "@/utils/encrypt";
import {CloseOutlined, EditOutlined, SearchOutlined} from "@ant-design/icons";

const {Option} = Select;

const selectParams = {
    deptId: "",
    ruleName: "",
    studentName: ""
}

let ruleId = '';
const RuleStudent: FC = () => {

    const columns = [
        {
            title: '学生姓名',
            key: 'studentName',
            dataIndex: 'studentName',
        },

        {
            title: '电话号码',
            key: 'phone',
            dataIndex: 'phone',
            render: (text: string) => <>{getOriginString(text)}</>
        },
        {
            title: '规则名称',
            key: 'ruleName',
            dataIndex: 'ruleName',
            editable: true,
        },
        {
            title: '规则状态',
            key: 'stateName',
            dataIndex: 'stateName',
            render: (text: string, record: any) => {
                const colorList = [
                    '#b7eb8f',
                    '#69c0ff',
                    '#ff7875',
                    '#5cdbd3',
                    '#69c0ff',
                    '#5cdbd3',
                    '#ff7875',
                    '#69c0ff',
                    '#ff7875',
                    '#ff7875',
                    '#ff7875',
                    '#ff7875',
                    '#ff7875',
                ]


                return <Tag color={colorList[Number(record.state) - 1]}>{record.stateName}</Tag>
            }
        },
        {
            title: '操作',
            render: (item: any, record: any) => {
                const editable = isEditing(record);

                return editable ? (<>
                    <Tag color={'#108ee9'} icon={<EditOutlined/>} onClick={() => save(record)}>
                        保存
                    </Tag>
                    <Popconfirm title="确定取消吗?" onConfirm={cancel}>
                        <Tag color={'#108ee9'} icon={<CloseOutlined/>}>取消</Tag>
                    </Popconfirm>
                </>) : (
                    record.state === 1 ? (
                            <Tag color={'#108ee9'} icon={<EditOutlined/>} onClick={() => edit(record)}>
                                修改
                            </Tag>)
                        : null
                );
            }

        },
    ]
    const studentInput = useRef<any>(null)
    const ruleInput = useRef<any>(null)
    const [treeNode, setTreeNode] = useState<any>([]);
    const [requestParamTree, setRequestParamTree] = useState<any>(
        {
            "level": 0,
            "treeId": "0"
        }
    );

    const [form] = Form.useForm();
    const [editingKey, setEditingKey] = useState('');
    const isEditing = (record: any) => record.id === editingKey;
    const cancel = () => {
        setEditingKey('');
    };
    const edit = (record: any) => {
        ruleId = '';
        form.setFieldsValue(record);
        setEditingKey(record.id);
    };


    const {
        tableProps,
        run,
        refresh
    } = useRequest(((current, params) => fetchRequest(url.RULE_USERINFO, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ...params

    })), {
        paginated: true,
        manual: true,
        formatResult: (response: any) => {
            return {
                list: response.data?.rows,
                total: response.data?.total,
                success: response.success,
                errorMsg: response.errorMsg
            };
        }
    })

    const {loading, run: updateRun} = useRequest((params) => fetchRequest(url.UPDATE_RULE_ID, params), {
        manual: true,
        onSuccess: async (result, params) => {
            if (result.success) {
                message.success(result.data)
                await refresh()
                cancel()
            } else {
                message.error(result.errorMsg)
            }
        }
    })

    const save = async (item: any) => {
        if (ruleId) {
            await updateRun({
                rule_id: ruleId,
                id: item.id
            })
        }
    }


    //搜索
    const onSearch = async () => {
        selectParams.studentName = studentInput.current!.state?.value
        selectParams.ruleName = ruleInput.current!.state?.value

        await run({pageSize: 10, current: 1}, {
            ...selectParams
        })
    }

    //修改
    const onEdit = (item: any) => {
        console.log(item)
    }

    //请求在校学生组织机构
    const getSchoolOrganizationRequest = async (params: any) => {
        try {
            const json = await fetchRequest(url.GET_SCHOOL_ORGANIZATION, params);
            if (json.success) {
                message.destroy();
                json.data.map((item: any) => {
                    delete item.children;
                });
                setTreeNode(json.data);

            } else {
                message.destroy();
                message.error(json.errorMsg)
            }
        } catch (error:any) {
            message.destroy();
            message.error(error.message)

        }
    }
    const loadData = async (selectedOptions: any) => {
        const targetOption = selectedOptions[selectedOptions.length - 1];
        targetOption.loading = true;

        //组装参数
        const params = {
            "level": 0,
            "treeId": "0"
        };
        selectedOptions.map((item: any) => {
            params.treeId = item.treeId;
            params.level = selectedOptions.length;
        });
        // console.log(params)

        fetchRequest(url.GET_SCHOOL_ORGANIZATION, params).then(json => {
            if (json.success) {
                console.log(json.data)
                json.data.map((item: any) => {
                    delete item.children;
                });
                targetOption.children = json.data;
                // console.log(targetOption)
            } else {
                message.error(json.errMsg);
            }
        }).catch(error => {
            console.log(error);
        }).finally(() => {
            targetOption.loading = false;
            //主动刷新页面
            setTreeNode([...treeNode]);
        });
    };
    const onChange = (value: any, selectedOptions: any) => {
        selectParams.deptId = value[value.length - 1]
    };
    useEffect(() => {
        getSchoolOrganizationRequest(requestParamTree)
    }, [requestParamTree])

    useEffect(() => {
        onSearch()
    }, [])


    const mergedColumns = columns.map(col => {
        if (!col.editable) {
            return col;
        }
        return {
            ...col,
            onCell: (record: any) => ({
                record,
                inputType: col.dataIndex === 'age' ? 'number' : 'text',
                dataIndex: col.dataIndex,
                title: col.title,
                editing: isEditing(record),
            }),
        };
    });


    return <>
        <div className={'rule-wrap'}>
            <div className={'search-wrap'}>
                <div>学生名称：</div>
                <div className={'search-value'}>
                    <Input ref={studentInput}/>
                </div>
                <div>规则名称：</div>
                <div className={'search-value'}>
                    <Input ref={ruleInput}/>
                </div>

                <div>组织机构：</div>
                <div>
                    <Cascader
                        style={{width: 400}}
                        placeholder="请选择组织机构"
                        options={treeNode}
                        loadData={loadData}
                        onChange={onChange}
                        changeOnSelect
                    />
                </div>
                <div>
                    <Button type={'primary'} onClick={onSearch} icon={<SearchOutlined/>}>搜索</Button>
                </div>
            </div>

            <Form form={form} component={false}>
                <Table
                    components={{body: {cell: EditableCell}}}
                    columns={mergedColumns}
                    rowKey="id"
                    {...tableProps as any}

                />
            </Form>


        </div>

    </>
}

const EditableCell: React.FC<any> = ({
                                         editing,
                                         dataIndex,
                                         title,
                                         inputType,
                                         record,
                                         index,
                                         children,
                                         ...restProps
                                     }) => {

    const {
        data,
        run,
        refresh,
        loading
    } = useRequest(((current) => fetchRequest(url.RULE_TABLE, {
        pageSize: current.pageSize,
        pageStart: current.current,
        ruleType: 1
    })), {
        paginated: true,
        manual: true,
        formatResult: (response: any) => {
            return {
                list: response.data?.rows,
                total: response.data?.total,
                success: response.success,
                errorMsg: response.errorMsg,
                page: response.data.page
            };
        }
    })
    const onPopupScroll = async (e: any) => {
        console.log(data)
        const {clientHeight, scrollHeight, scrollTop} = e.target
        if (clientHeight + scrollTop === scrollHeight && !loading) {
            await run({pageSize: 10, current: data?.page + 1})
        }
    }
    const onFocus = async () => {
        await run({pageSize: 10, current: 1})
    }

    const onSelect = (value: any) => {
        ruleId = value;
    }

    const inputNode = <>
        <Select onPopupScroll={onPopupScroll} onSelect={onSelect} onFocus={onFocus} defaultValue={[record?.ruleName]}
                loading={loading}>
            {data?.list?.map((item: any) => <Option key={item.id} value={item.id}>{item.ruleName}</Option>)}
        </Select>
    </>

    return (
        <td {...restProps}>
            {editing ? (
                <Form.Item
                    name={dataIndex}
                    style={{margin: 0}}
                    rules={[
                        {
                            required: true,
                            message: `Please Input ${title}!`,
                        },
                    ]}
                >
                    {inputNode}
                </Form.Item>
            ) : (
                children
            )}
        </td>
    );
};

export default RuleStudent
